package br.usp.ime.dojo.client;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class RoomListing extends Composite {
	

	private VerticalPanel pnlRoomList;
	private VerticalPanel pnlRoomList2;
	private HorizontalPanel hPanel;
	private Label lblTitle;
	private VerticalPanel panel;
	private DojoRoomServiceAsync roomListingSvc;
	private JoinARoomListener joinARoomListener;
	
	public RoomListing() {
		

		pnlRoomList = new VerticalPanel();
		pnlRoomList2 = new VerticalPanel();
		
		pnlRoomList.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		
		// TODO - Arrumar o jeito de centralizar as colunas
		
		hPanel = new HorizontalPanel();
		hPanel.add(pnlRoomList);
		hPanel.add(pnlRoomList2);
		
		lblTitle = new Label("Dojo Room List");
		lblTitle.addStyleName("title");

		Timer refreshTimer = new Timer(){
			public void run() {
				refreshDojoRoomList();
			}			
		};
		refreshTimer.scheduleRepeating(2000);
		
		refreshDojoRoomList();
		
		panel = new VerticalPanel();
				
		panel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
	    panel.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE);

		panel.add(lblTitle);
		panel.add(hPanel);

		initWidget(panel);		
	}

	protected void refreshDojoRoomList() {
		if(roomListingSvc == null){
			roomListingSvc = GWT.create(DojoRoomService.class);
		}
		AsyncCallback< ArrayList<DojoRoomDTO> > callback = new AsyncCallback<ArrayList<DojoRoomDTO> >() {
			public void onFailure(Throwable caught) {
			}

			public void onSuccess(ArrayList<DojoRoomDTO> result) {

				pnlRoomList.clear();
				pnlRoomList2.clear();
				if(result != null){
					int i = 0;
					for( DojoRoomDTO dojoRoomDTO : result){
						RoomInfo roomInfo = new RoomInfo(dojoRoomDTO);
						roomInfo.setJoinRequestListener(joinARoomListener);
						
						if(i%2 == 0){
							pnlRoomList.add(roomInfo);
						} else
							pnlRoomList2.add(roomInfo);
						
						i++;
					}			
				}
			}
		};

		roomListingSvc.getDojoRoomList(callback);
	}

	public void setJoinRequestListener(JoinARoomListener dojoOnline) {
		joinARoomListener = dojoOnline;
		
	}

}
